package cn.bluedot.tea.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import cn.bluedot.common.redis.JedisPoolCacheUtils;
import cn.bluedot.framework.web.Result;
import cn.bluedot.tea.dao.BaseDao;
import cn.bluedot.tea.filter.changeresponse.AuthCodeResponseWrapper;
import cn.bluedot.tea.pojo.domain.LoginLog;
import cn.bluedot.tea.util.AddressUtils;
import cn.bluedot.tea.util.ClientInfoUtil;
import cn.bluedot.tea.util.DateUtil;
import redis.clients.jedis.Jedis;

public class LoginLogFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		String email = req.getParameter("email");
		String userIp = ClientInfoUtil.getIPAddress(req);
		String systemName = ClientInfoUtil.getOsName(req);// 得到用户的浏览器名  
		String browserName = ClientInfoUtil.getBrowserName(req);// 得到用户的操作系统名
		LoginLog loginLog = new LoginLog(email, userIp, browserName, systemName, DateUtil.getDateTime());

		// 获取返回给客户端的消息
		AuthCodeResponseWrapper responseWrapper = new AuthCodeResponseWrapper((HttpServletResponse) response);
		chain.doFilter(request, responseWrapper);// 放行
		ServletOutputStream out = response.getOutputStream();
		String content = responseWrapper.getTextContent();
		out.write(content.getBytes());//将缓存的字符串写回到输出流当中
		@SuppressWarnings("unchecked")
		Map<String, Object> msgMap = (Map<String, Object>) JSONObject.parse(content);
		loginLog.setMessage((String) msgMap.get("message"));
		loginLog.setResult((String) msgMap.get("RESULT"));

		Thread loggerThread = new LoggerThread(loginLog);
		loggerThread.start();

	}

	public void destroy() {
	}

	private class LoggerThread extends Thread {

		private LoginLog loginLog;

		public LoggerThread(LoginLog loginLog) {
			this.loginLog = loginLog;
		}

		@SuppressWarnings("unchecked")
		private String getRoleName(String email) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("view", "getRoleByEmail");
			param.put("email", email);
			String roleName = "其他";
			try {
				roleName = (String) ((ArrayList<LinkedHashMap<String, Object>>) BaseDao.excuteQuery(param, null)).get(0)
						.get("roleName");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return roleName;
		}
		
		private String getRoleNameByRedis(String email) {
			Jedis jedis = JedisPoolCacheUtils.getResource();
			String roleName  = jedis.get("roleName:" + email);
			if (roleName == null || "".equals(roleName.trim())) {
				roleName = getRoleName(email);
				jedis.set("roleName:" + email, roleName, "NX", "EX", JedisPoolCacheUtils.EXRP_HOUR);
			}
			jedis.close();
			return roleName;
		}
		
		@Override
		public void run() {
			if (loginLog.getMessage() == null && Result.SUCCESS.equals(loginLog.getResult())) {
				loginLog.setMessage("登陆成功");
			} else if (loginLog.getMessage() == null && Result.FAILED.equals(loginLog.getResult())) {
				loginLog.setMessage("登陆异常");
			}

			loginLog.setAddress(AddressUtils.getAddrssessUTF8ByReids(loginLog.getUserIp()));
			loginLog.setRoleName(getRoleNameByRedis(loginLog.getEmail()));

			Map<String, Object> param = new HashMap<String, Object>();
			// 将日志存入数据库当中
			param.put("view", "insertLoginLog");
			param.put("email", loginLog.getEmail());
			param.put("roleName", loginLog.getRoleName());
			param.put("userIp", loginLog.getUserIp());
			param.put("address", loginLog.getAddress());
			param.put("browserName", loginLog.getBrowserName());
			param.put("systemName", loginLog.getSystemName());
			param.put("message", loginLog.getMessage());
			param.put("result", loginLog.getResult());
			param.put("loginTime", loginLog.getLoginTime());
			try {
				BaseDao.excute(param);
			} catch (Exception e) {
				System.out.println("数据库查询出现异常.....");
				e.printStackTrace();
			}
		}

	}

}
